package com.csi.service.impl;

import com.csi.domain.User;
import com.csi.mapper.UserMapper;
import com.csi.service.UserService;
import com.csi.utils.MD5Utils;
import com.csi.utils.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public User findByUsername(String username) {
        User user = userMapper.findByName(username);
        return user;
    }

    @Override
    public User login(String username, String password) {
//        password = MD5Utils.getMD5String(password);
        User user =  userMapper.login(username,password);
        return user;
    }

    @Override
    public boolean reg(User user, MultipartFile photo) {
        if (photo!=null && photo.getSize()>0) {
            String originalFilename = photo.getOriginalFilename();
            String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString()+extname;
            InputStream is = null;
            try {
                is = photo.getInputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String photos = OssUtil.upload(filename, is, "user");
            user.setUserHead(photos);

        }
//        user.setPassword(MD5Utils.getMD5String(user.getPassword()));
        return userMapper.add(user)==1;
    }

    @Override
    public User getUser(long userId) {
        return userMapper.getUser(userId);
    }
}
